#!/bin/bash

NETWORK_NAME="feshop_sys_network"

# 检查网络是否存在 
if docker network ls --format "{{.Name}}" | grep -q "^${NETWORK_NAME}$"; then
    echo "网络 '${NETWORK_NAME}' 已存在，跳过创建。"
else
    echo "正在创建网络 '${NETWORK_NAME}'..."
    docker network create \
        --driver bridge \
        ${NETWORK_NAME}

    if [ $? -eq 0 ]; then
        echo "网络 '${NETWORK_NAME}' 创建成功。"
    else
        echo "网络 '${NETWORK_NAME}' 创建失败。"
        exit 1
    fi
fi

# 仓库根目录
REPO_ROOT="/var/lib/jenkins/workspace/zlj.dapr.microserviceproject"

# 处理命令行参数
FORCE_UPDATE=0
while getopts ":f" opt; do
  case $opt in
    f)
      FORCE_UPDATE=1
      echo "⚠️ 强制更新模式: 将更新所有服务"
      ;;
    \?)
      echo "⚠️ 无效选项: -$OPTARG" >&2
      ;;
  esac
done

# 获取最近两次提交的变更文件
CHANGED_FILES=$(git diff --name-only HEAD~1 HEAD 2>/dev/null)

# 定义服务目录映射
declare -A SERVICE_PATHS=(
    ["FEShop.Infrastructure"]="02-FEShop.Infrastructure/FEShop.Infrastructure/components"
    ["FEShop.UserService"]="03-FEShop.Microservices/FEShop.AppUserService"
    ["FEShop.ProductService"]="03-FEShop.Microservices/FEShop.ProductService"
    ["FEShop.OrderService"]="03-FEShop.Microservices/FEShop.OrderService"
    ["FEShop.PaymentService"]="03-FEShop.Microservices/FEShop.PaymentService"
    ["FEShop.AdminWebSite"]="06-FEShop.WebSite/FEShop.AdminWebSite"
    ["FEShop.PCShop"]="06-FEShop.WebSite/FEShop.PCShop"
    ["FEShop.Gateway"]="05-FEShop.Gateway/FEShop.GatewayApi"
)

# 定义公共库（变更时触发所有服务）
COMMON_LIBS=("01-FEShop.Common" "02-FEShop.Infrastructure" "04-FEShop.Shared")

# 存储需要更新的服务
declare -A SERVICES_TO_UPDATE

# 0. 强制更新模式处理
if [ $FORCE_UPDATE -eq 1 ]; then
    echo "⚠️ 强制更新所有服务"
    for service in "${!SERVICE_PATHS[@]}"; do
        SERVICES_TO_UPDATE["$service"]=1
    done
else
    # 1. 检查公共库是否变更
    for lib in "${COMMON_LIBS[@]}"; do
        if echo "$CHANGED_FILES" | grep -q "^$lib"; then
            echo "公共库 $lib 变更，将部署所有微服务"
            for service in "${!SERVICE_PATHS[@]}"; do
                SERVICES_TO_UPDATE["$service"]=1
            done
            break
        fi
    done

    # 2. 检查各微服务变更
    if [ ${#SERVICES_TO_UPDATE[@]} -eq 0 ]; then
        for service in "${!SERVICE_PATHS[@]}"; do
            service_path="${SERVICE_PATHS[$service]}"

            # 检查该服务目录或其子目录是否有变更
            if echo "$CHANGED_FILES" | grep -q "^$service_path"; then
                echo "检测到变更: $service"
                SERVICES_TO_UPDATE["$service"]=1
            fi
        done
    fi
fi

# 清理Dapr sidecar容器
cleanup_dapr_sidecars() {
    local service_name=$1
    local app_id="feshop-${service_name,,}"  # 转换为小写
    
    echo "🧹 清理Dapr sidecar容器: $app_id"
    
    # 查找并停止所有相关的sidecar容器
    sudo docker ps -a --filter "name=.*${app_id}-sidecar-*" --format "{{.Names}}" | while read container; do
        echo "🛑 停止并移除sidecar容器: $container"
        sudo docker stop "$container" >/dev/null 2>&1
        sudo docker rm "$container" >/dev/null 2>&1
    done
}

# 3. 执行部署
deploy_service() {
    local service_name=$1
    local service_path="${REPO_ROOT}/${SERVICE_PATHS[$service_name]}"
    local container_name="dapr-${service_name,,}"  # 转换为小写

    echo "========================================"
    echo "开始部署 $service_name"
    echo "目录: $service_path"
    echo "========================================"

    cd "$service_path" || { echo "❌ 无法进入目录: $service_path"; return 1; }

    # 清理Dapr sidecar容器
    cleanup_dapr_sidecars "$service_name"

    # 检查容器是否存在，避免停止/移除时报错
    if sudo docker ps -a --format '{{.Names}}' | grep -q "^${container_name}$"; then
        echo "🛑 停止并移除旧容器: $container_name"
        sudo docker stop "$container_name" >/dev/null 2>&1
        sudo docker rm "$container_name" >/dev/null 2>&1
    else
        echo "ℹ️ 容器不存在，无需停止: $container_name"
    fi

    # 检查镜像是否存在
    if sudo docker images --format '{{.Repository}}:{{.Tag}}' | grep -q "^${container_name}:v1.0.1$"; then
        echo "🗑️ 移除旧镜像: ${container_name}:v1.0.1"
        sudo docker rmi "${container_name}:v1.0.1" >/dev/null 2>&1
    fi

    # 构建并启动新容器
    echo "🚀 重新构建并启动容器"
    docker-compose up -d --build

    if [ $? -eq 0 ]; then
        echo "✅ $service_name 部署成功"
    else
        echo "❌ $service_name 部署失败"
    fi

    echo ""
}

# 部署所有变更的服务
if [ ${#SERVICES_TO_UPDATE[@]} -gt 0 ]; then
    echo "需要更新的服务: ${!SERVICES_TO_UPDATE[@]}"
    for service in "${!SERVICES_TO_UPDATE[@]}"; do
        deploy_service "$service"
    done
else
    echo "⚠️ 未检测到需要更新的微服务"
fi